﻿using BJoin.Application.AppException;
using BJoin.Application.BObject;
using BJoin.Application.Dto;
using BJoin.Common;
using BJoin.MicroSVC.Sample.DataContract.Entities;
using BJoin.MicroSVC.Sample.DataContract.Dtos;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BJoin.MicroSVC.Sample.DataContract.ExtObjects;
namespace BJoin.MicroSVC.Sample.Core.Managers
{
    public partial interface IFileManager
    {
        Task<FileDto> GetFileWithFormatDesc(long id);
        Task<string> DownloadAsync(long id);
        Task<bool> UploadAsync(IList<IFormFile> files);
        Task<ResPagingDto<FileDto>> GetFileTranslater(FileFilter filter, int pageIndex, int pageSize, string[] orderBy = null);
    }
    public partial class FileManager:IFileManager
    {
        //private IFilePageRepository filePageRepository;
        partial void Init()
        {
            //init other repository
            //filePageRepository = ServiceProvider.GetService<IFilePageRepository>() ?? throw new Exception($"{nameof(IFilePageRepository)} init fail");
        }

        #region BizValidater
        protected override async Task BizValidaterAsync<FileAddDto>(FileAddDto addDto)
        {
            var entity = Mapper.Map<FileEntity>(addDto);
            await ValidationDisplay(new List<FileEntity> { entity }, exists =>
            {
                if (exists.IsAny())
                    return EnumMessage.ExistCannotDuplicate;
                return EnumMessage.OK;
            }, true);
        }
        protected override async Task BizValidaterAsync<FileAddDto>(IEnumerable<FileAddDto> addDtos)
        {
            var entities = Mapper.Map<IEnumerable<FileEntity>>(addDtos);
            await ValidationDisplay(entities, exists =>
            {
                if (exists.IsAny())
                    return EnumMessage.ExistCannotDuplicate;
                return EnumMessage.OK;
            }, true);
        }
        protected override async Task BizValidaterAsync<FileUpdateDto>(FileUpdateDto updateDto, long id)
        {
            var entity = Mapper.Map<FileEntity>(updateDto);
            await ValidationDisplay(new List<FileEntity> { entity }, exists =>
            {
                if (exists.IsAny(es => es.Id != id))
                    return EnumMessage.ExistCannotDuplicate;
                return EnumMessage.OK;
            }, string.IsNullOrWhiteSpace(entity.Code));
        }
        private async Task ValidationDisplay(IEnumerable<FileEntity> entities, Func<IEnumerable<FileEntity>, EnumMessage> func, bool isValidation)
        {
            if (isValidation && entities.IsAny())
            {
                var exists = await ReadAsync(async database => await Repository.GetListAsync(database,0,1, new FileFilter
                {
                    //不能重复字段
                    Code = entities.Select(e => e.Code).ToArray()
                }));
                if (exists.IsAny())
                {
                    switch (func(exists))
                    {
                        case EnumMessage.ExistCannotDuplicate:
                            throw new HttpStatusCodeException(StatusCodes.Status400BadRequest,
                               string.Format(EnumHelper.GetEnumDescription<EnumMessage>(EnumMessage.ExistCannotDuplicate), nameof(FileEntity.Code)));
                    }
                }
            }

        }
        #endregion
        public async Task<ResPagingDto<FileDto>> GetFileTranslater(FileFilter filter, int pageIndex, int pageSize, string[] orderBy = null)
        {
            var list = await PagingFilterAsync(filter, pageIndex, pageSize, orderBy,
                filter => FilterTranslater(filter),
                async data => await DataTransalter(data));
            return list;
        }
        private object FilterTranslater(FileFilter filter)
        {
            filter.FileFormat = EnumFileFormat.Pdf;
            return filter;
        }
        private async Task DataTransalter(List<FileDto> data)
        {
            var file = await GetSingleAsync(1);
            data.ForEach(d =>
            {
                d.FileFormatDesc = null == file ? string.Empty : EnumHelper.GetEnumDescription(d.FileFormat);
                d.Crt = d.Crt.ToUniversalTime();
                d.Upt = d.Upt.ToUniversalTime();
            });
        }
        public async Task<FileDto> GetFileWithFormatDesc(long id)
        {
            var result = await GetFileWithChild();
            return await GetSingleAsync(id, async f =>
            {
                var list = await FilterAsync(f => f.Id == 736151116688916480);
                f.FileFormatDesc = EnumHelper.GetEnumDescription(f.FileFormat);
            });
        }

        private async Task<ResPagingDto<FileWithChildDto>> GetFileWithChild()
        {
            var pagingFiles = await PagingFilterAsync(new FileFilter { }, 0, 1,null);
            var pagingFxDto = Mapper.Map<ResPagingDto<FileWithChildDto>>(pagingFiles);
            pagingFxDto.Items.AsList().ForEach(fx =>
            {
                fx.ChildFiles = new List<FileDto>();
            });
            return pagingFxDto;
        }
        /// <summary>
        /// 返回文件全路径
        /// </summary>
        /// <param name="id"></param>
        /// <returns>file path</returns>
        public async Task<string> DownloadAsync(long id)
        {
            var file = await GetSingleAsync(id);
            return file?.Ext?.Url;
        }

        public Task<bool> UploadAsync(IList<IFormFile> files)
        {
            throw new NotImplementedException();
        }
        public override Task<bool> UpdateSetAsync<FileUpdateDto>(FileUpdateDto updateDto, long id)
        {
            FileUpdateDto update = updateDto as FileUpdateDto;
            if (update != null)
            {
            }
            return base.UpdateSetAsync(updateDto,id);
        }
    }
}
